#include "toralize.h"

Req *request(const char *dstip, const int dstport) {
    Req *req;
    req = malloc(reqsize);
    req->vn = 4;
    req->cd = 1;
    req->dstport = htons(dstport);
    req->dstip = inet_addr(dstip);
    strncpy((char *) req->userid, USERNAME, 8);
    return req;
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <host> <port>\n", argv[0]);
        return -1;
    }

    char *host = argv[1];
    int port = atoi(argv[2]);// more: man 3 atoi

    //create descriptor
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        perror("fail to call socket()");
        return -1;
    }

    struct sockaddr_in sock;
    sock.sin_family = AF_INET;
    sock.sin_port = htons(PROXY_PORT);
    sock.sin_addr.s_addr = inet_addr(PROXY);

    //connect to proxy server
    if (connect(s, (struct sockaddr *) &sock, sizeof(sock))) {
        perror("fail to connect proxy server");
        return -1;
    }
    printf("connect to proxy server successfully!\n");

    // write
    Req *req = request(host, port);
    write(s, req, reqsize);

    // read
    char buf[ressize];
    memset(buf, 0, ressize);
    if (read(s, buf, ressize) < 1) {
        perror("fail to read.\n");
        free(req);
        close(s);
        return -1;
    }
    Res *res = (Res *) buf;
    if (res->cd != 90) {
        fprintf(stderr, "unable to traverse the proxy, error code(cd) is %d.\n", res->cd);
        free(req);
        close(s);
        return -1;
    }
    printf("successfully connect through the proxy to %s:%d.\n", host, port);

    // send HEAD request
    char tmp[1024];
    memset(tmp, 0, 1024);
    snprintf(tmp, 1023,
             "HEAD / HTTP/1.0\r\n"
             "Host: networktechnology.org\r\n"
             "\r\n");
    write(s, tmp, strlen(tmp));
    // receive
    memset(tmp, 0, 1024);
    read(s, tmp, 1023);
    printf("---- response ----\n'%s'\n", tmp);

    free(req);
    close(s);
    return 0;
}
